<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
        <el-form-item label="发票代码" prop="invoiceCode">
          <el-input
            v-model="queryParams.invoiceCode"
            placeholder="请输入发票代码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="收票日期" prop="params">
          <el-date-picker
            clearable
            v-model="queryParams.params"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            placeholder="请选择收票日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商名称" prop="vendorName">
          <el-input
            v-model="queryParams.vendorName"
            placeholder="请输入供应商名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cg:invoice:add']"
          >新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="invoiceList">
        <el-table-column label="发票号码" align="center" prop="invoiceNumber"/>
        <el-table-column label="发票代码" align="center" prop="invoiceCode"/>
        <el-table-column label="供应商" align="center" prop="vendorName"/>
        <el-table-column label="发票金额" align="center" prop="invoiceAmount"/>
        <el-table-column label="发票类型" align="center" prop="invoiceType"/>
        <el-table-column label="收票人" align="center" prop="invoiceReceivePerson"/>
        <el-table-column label="收票日期" align="center" prop="invoiceReceiveDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.invoiceReceiveDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleView(scope.row)"
                v-hasPermi="['cg:invoice:query']"
              >查看
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-check"
                @click="handleConfirm(scope.row)"
                v-show="scope.row.status === 'PREPARE'||scope.row.status === 'DISALLOW'"
                v-hasPermi="['cg:invoice:confirm']"
              >确认
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-show="scope.row.status === 'PREPARE'|| scope.row.status === 'DISALLOW'"
                v-hasPermi="['cg:invoice:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['cg:invoice:remove']"
                v-show="scope.row.status === 'PREPARE'||scope.row.status === 'DISALLOW'"
              >删除
              </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改采购发票对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传发票" prop="invoiceUrl">
              <FileUpload
                :limit="1"
                :fileSize="100"
                :fileType="fileType"
                :value="fileList"
                :optType="optType"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"
                           :disabled="form.isReturn==='Y'"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="form.invoiceType" placeholder="请选择发票类型" style="width:100%">
                <el-option label="普通发票" value="普通发票"/>
                <el-option label="专用发票" value="专用发票"/>
                <el-option label="红字专用发票" value="红字专用发票"/>
                <el-option label="红字普通发票" value="红字普通发票"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="form.invoiceCode" placeholder="请输入发票代码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收票日期" prop="invoiceReceiveDate">
              <el-date-picker clearable
                              v-model="form.invoiceReceiveDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择收票日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收票人" prop="invoiceReceivePerson">
              <el-input v-model="form.invoiceReceivePerson" placeholder="请选择收票人" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectUser"
                  icon="el-icon-search">
                </el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input v-model="form.invoiceAmount" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 25px; margin-top: 3px">发票明细</div>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" style="margin-left: 20px;" @click="handleAddCgInvoiceLine" v-show="form.vendorId">
              选择单据
            </el-button>
          </el-col>
        </el-row>
        <el-table border :data="cgInvoiceLineList" ref="cgInvoiceLine" show-summary :summary-method="getSummaries">
          <el-table-column label="产品编码" align="center" prop="itemCode"/>
          <el-table-column label="产品名称" align="center" prop="itemName"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
          <el-table-column label="发票数量" align="center" prop="quantity" width="200">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1" :max="scope.row.notInvoicedQuantity"
                               size="mini" style="width:130px"
                               @change="handleEdit(scope.$index, scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="不含税单价" align="center" prop="price"/>
          <el-table-column label="金额" align="center" prop="amount" width="200">
            <template slot-scope="scope">
              <el-input-number class="item__input" v-model="scope.row.amount" placeholder="请输入金额"
                               size="mini" style="width:150px"
                               :min="1"
                               :precision="2"
                               controls-position="right"
                               @change="handleEdit(scope.$index, scope.row)"></el-input-number>
            </template>

          </el-table-column>
          <el-table-column label="税率" align="center" prop="taxRate">
              <div class="item" slot-scope="scope">
              <el-select v-model="scope.row.taxRate" placeholder="请选择税率" style="width:100%">
                <el-option v-for="item in taxRateList" :key="item.taxRate" :value="item.taxRate" :label="item.taxRate">
                </el-option>
              </el-select>
              </div>
          </el-table-column>
          <el-table-column label="税额" align="center" prop="taxAmount" width="200">
            <template slot-scope="scope">
              <el-input-number class="item__input" v-model="scope.row.taxAmount" placeholder="请输入税额"
                               size="mini" style="width:150px"
                               :min="1"
                               :precision="2"
                               controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="入库单号" align="center" prop="recptCode"/>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDeleteCgInvoiceLine(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    选择单据对话框-->
    <el-dialog title="选择单据" :visible.sync="openReceiptSelect" width="80%" append-to-body>
      <el-card style="border-radius: 10px">
        <el-form :model="receiptQueryParams" ref="receiptQueryForm" size="small" :inline="true" v-show="true"
                 label-width="120px">
          <el-form-item label="入库单号" prop="recptCode">
            <el-input
              v-model="receiptQueryParams.recptCode"
              placeholder="请输入入库单号"
              clearable
              @keyup.enter.native="handleReceiptQuery"
            />
          </el-form-item>
          <el-form-item label="产品名称" prop="itemName">
            <el-input
              v-model="receiptQueryParams.itemName"
              placeholder="请输入产品名称"
              clearable
              @keyup.enter.native="handleReceiptQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleReceiptQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetReceiptQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <div style="height: 15px"></div>
      <el-card style="border-radius: 10px">
        <el-table border :data="receiptList" ref="receiptTable" @selection-change="handleSelectionChange" height="550">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="入库单号" align="center" prop="recptCode"/>
          <el-table-column label="供应商" align="center" prop="vendorName"/>
          <el-table-column label="入库日期" align="center" prop="recptDate">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料编号" align="center" prop="itemCode"/>
          <el-table-column label="物料名称" align="center" prop="itemName"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
          <el-table-column label="入库数量" align="center" prop="quantity"/>
          <el-table-column label="单价" align="center" prop="price"/>
          <el-table-column label="未开票数量" align="center" prop="notInvoicedQuantity"/>
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveReceipt">确 定</el-button>
        <el-button @click="openReceiptSelect=false">取 消</el-button>
      </div>
    </el-dialog>
    <!--    采购发票审批-->
    <el-dialog :title="title" :visible.sync="openConfirm" width="80%" append-to-body>
      <el-form ref="confirmForm" :model="form" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="发票" prop="invoiceUrl">
              <FileUpload
                :limit="1"
                :fileSize="100"
                :fileType="fileType"
                :value="fileList"
                :optType="optType"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved">
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-input v-model="form.invoiceType" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" readonly="readonly"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="form.invoiceCode" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收票日期" prop="invoiceReceiveDate">
              <el-date-picker clearable
                              v-model="form.invoiceReceiveDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择收票日期"
                              style="width: 100%" readonly="readonly">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收票人" prop="invoiceReceivePerson">
              <el-input v-model="form.invoiceReceivePerson" readonly="readonly"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票金额" prop="invoiceAmount">
              <el-input v-model="form.invoiceAmount" readonly="readonly" style="width:100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row style="margin-bottom: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 25px; margin-top: 3px">发票明细</div>
          </el-col>
        </el-row>
        <el-table border :data="cgInvoiceLineList" ref="cgInvoiceLine" show-summary :summary-method="getSummaries">
          <el-table-column label="产品编码" prop="itemCode"/>
          <el-table-column label="产品名称" prop="itemName"/>
          <el-table-column label="单位" prop="unitOfMeasure"/>
          <el-table-column label="发票数量" prop="quantity"/>
          <el-table-column label="不含税单价" prop="price"/>
          <el-table-column label="金额" prop="amount"/>
          <el-table-column label="税率" prop="taxRate"/>
          <el-table-column label="税额" prop="taxAmount"/>
          <el-table-column label="入库单号" prop="recptCode"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmForm" v-if="confirmBtn">确认</el-button>
        <el-button @click="openConfirm=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInvoice,
  getInvoice,
  delInvoice,
  addInvoice,
  updateInvoice,
  listReceipt,
  confirmInvoice,
  getTaxRateSelectData
} from "@/api/mes/cg/invoice";
import VendorSelect from "@/components/vendorSelect/single.vue";
import UserSelect from "@/components/userSelect/single.vue";
import {getUser, getUserProfile} from "@/api/system/user";

export default {
  name: "Invoice",
  components: {UserSelect, VendorSelect},
  dicts: ['mes_order_status'],
  data() {
    return {
      optType: undefined,
      confirmBtn:true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购发票表格数据
      invoiceList: [],
      // 采购发票明细表格数据
      cgInvoiceLineList: [],
      taxRateList:[],
      taxRateDefault: null,
      receiptList: [],
      selectedRows: [],
      selectedRows1: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openReceiptSelect: false,
      openConfirm: false,
      receiptQueryParams: {
        itemName: null,
        recptCode: null,
        vendorId: null,
        invoiceId: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        invoiceType: null,
        invoiceNumber: null,
        invoiceCode: null,
        invoiceReceiveDate: null,
        invoiceReceivePerson: null,
        vendorName: null,
        params:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        invoiceUrl: [
          {required: true, message: "请上传发票", trigger: "blur"}
        ],
        vendorName: [
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
        invoiceType: [
          {required: true, message: "请选择发票类型", trigger: "blur"}
        ],
        invoiceNumber: [
          {required: true, message: "请填写发票号码", trigger: "blur"}
        ],
        invoiceCode: [
          {required: true, message: "请填写发票代码", trigger: "blur"}
        ],
        invoiceReceiveDate: [
          {required: true, message: "请选择收票日期", trigger: "blur"}
        ],
        invoiceReceivePerson: [
          {required: true, message: "请填写收票人", trigger: "blur"}
        ],
        invoiceAmount: [
          {required: true, message: "请填写发票金额", trigger: "blur"}
        ],
      },
      // 上传文件类型
      fileType: ["pdf", "jpg", "png", "jpeg"],
      // 上传文件列表
      fileList: [],
      user: {},
    };
  },
  created() {
    this.getList();
    this.getRaxRateSelectData();
    this.getUser();
  },
  methods: {
    /** 查询采购发票列表 */
    getList() {
      const query = { ...this.queryParams };
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      this.loading = true;
      listInvoice(query).then(response => {
        this.invoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        invoiceType: null,
        invoiceNumber: null,
        invoiceCode: null,
        invoiceReceiveDate: new Date().toISOString().split('T')[0],
        invoiceReceivePerson: null,
        invoiceReceivePersonId: null,
        invoiceAmount: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        status: "PREPARE",
        invoiceUrl: null
      };
      this.cgInvoiceLineList = [];
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleReceiptQuery() {
      this.getReceiptList();
    },
    /** 重置按钮操作 */
    resetReceiptQuery() {
      this.resetForm("receiptQueryForm");
      this.receiptQueryParams.invoiceId = this.form.id;
      this.receiptQueryParams.vendorId = this.form.vendorId;
      this.receiptQueryParams.recptCode=null;
      this.receiptQueryParams.itemName=null;
      this.handleReceiptQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.optType = "add";
      this.open = true;
      this.title = "添加采购发票";
      this.form.invoiceReceivePerson=this.user.userName;
      this.form.invoiceReceivePersonId=this.user.userId;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.optType = "edit";
      const id = row.id || this.ids
      getInvoice(id).then(response => {
        this.form = response.data;
        response.data.invoiceUrl == null ? this.fileList = [] : this.fileList.push(response.data.invoiceUrl);

        this.cgInvoiceLineList = response.data.cgInvoiceLineList;
        this.open = true;
        this.title = "修改采购发票";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.cgInvoiceLineList = this.cgInvoiceLineList;
          if (this.form.id != null) {
            updateInvoice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInvoice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购发票编号为"' + ids + '"的数据项？').then(function () {
        return delInvoice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 采购发票明细添加按钮操作 */
    handleAddCgInvoiceLine() {
      this.openReceiptSelect = true;
      this.receiptQueryParams.invoiceId = this.form.id;
      this.receiptQueryParams.vendorId = this.form.vendorId;
      this.selectedRows1 = this.cgInvoiceLineList;
      this.getReceiptList();
    },
    /** 采购发票明细删除按钮操作 */
    handleDeleteCgInvoiceLine(row) {
      this.cgInvoiceLineList.splice(this.cgInvoiceLineList.indexOf(row), 1);
    },
    /** 导出按钮操作 */
    /*handleExport() {
      this.download('invoice/invoice/export', {
        ...this.queryParams
      }, `invoice_${new Date().getTime()}.xlsx`)
    },*/
    handleUploaded(data) {
      this.form.invoiceUrl = data;
    },
    handleRemoved(data) {
      this.form.invoiceUrl = data;
    },
    //供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    //供应商选择弹出框
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
      }
    },
    getReceiptList() {
      listReceipt(this.receiptQueryParams).then(response => {
        this.receiptList = response.data;
        this.$nextTick(function () {
          if (this.selectedRows1.length > 0) {
            this.selectedRows1.forEach(row => {
              let data = this.receiptList.find(item => item.recptLineId == row.recptLineId);
              if (data) {
                this.$refs.receiptTable.toggleRowSelection(data);
              }

            })
          }
        })
        this.loading = false;
      });
    },
    handleSelectionChange(val) {
      val.forEach(item=>{
        item.taxRate=this.taxRateDefault;
      })
      this.selectedRows = val;
    },
    saveReceipt() {
      if (this.cgInvoiceLineList.length && this.cgInvoiceLineList.length > 0) {
        this.cgInvoiceLineList.forEach((item, index) => {
          this.selectedRows.find((item1) => {
            if (item.recptLineId == item1.recptLineId) {
              item1.taxRate = item.taxRate;
            }
          })
        })
      }
      this.cgInvoiceLineList = this.selectedRows;
      this.openReceiptSelect = false;
    },
    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      let amountNum = 0;
      let taxAmountNum = 0;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "金额合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "amount"
        ) {
          amountNum = index;
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }else if (column.property === "taxAmount") {
          taxAmountNum = index;
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      this.form.invoiceAmount=sums[amountNum]+sums[taxAmountNum];
      return sums;
    },
    handleConfirm(row) {
      this.cgInvoiceLineList = [];
      this.fileList = [];
      this.resetForm("confirmForm");
      this.optType = "view";
      this.title='确认';
      this.confirmBtn=true;
      const id = row.id || this.ids
      getInvoice(id).then(response => {
        this.form = response.data;
        response.data.invoiceUrl == null ? this.fileList = [] : this.fileList.push(response.data.invoiceUrl);
        this.cgInvoiceLineList = response.data.cgInvoiceLineList;
        this.openConfirm = true;
      });
    },
    handleView(row) {
      this.cgInvoiceLineList = [];
      this.fileList = [];
      this.resetForm("confirmForm");
      this.optType = "view";
      this.title='查看';
      this.confirmBtn=false;
      const id = row.id || this.ids
      getInvoice(id).then(response => {
        this.form = response.data;
        response.data.invoiceUrl == null ? this.fileList = [] : this.fileList.push(response.data.invoiceUrl);
        this.cgInvoiceLineList = response.data.cgInvoiceLineList;
        this.openConfirm = true;
      });
    },
    confirmForm() {
      confirmInvoice(this.form.id).then(response => {
        this.openConfirm = false;
        this.cgInvoiceLineList = [];
        this.fileList = [];
        this.resetForm("confirmForm");
        this.getList();
      })
    },
    getRaxRateSelectData(){
      const query={
        isOpen:0,
        taxType:'进项税'
      }
      getTaxRateSelectData(query).then(response => {
        this.taxRateList = response.data;
        this.taxRateList.forEach(item=>{
          if(item.isDefault===0){
            this.taxRateDefault=item.taxRate;
          }
        })
      })
    },
    //商品单价
    handleEdit(index, row) {
      if (row.quantity && row.amount) {
        row.price = parseFloat(Number(row.amount) / Number(row.quantity)).toFixed(2)
      }
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.invoiceReceivePersonId = obj.userId;
        this.form.invoiceReceivePerson = obj.nickName;
      }
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
  }
};
</script>
